using System;
using System.Collections.Generic;
using System.Linq;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using dbvc.data;

namespace dbvc.Queries
{
    public class ProjectQuery : GenericQuery<db_project>
    {
        private static readonly Func<DAA, int, IQueryable<db_script>> cGetVersionScripts =
            CompiledQuery.Compile((DAA db, int ver_id) =>
                                  db.GetTable<db_script>().Where(
                                      s => db.GetTable<db_version_script>()
                                               .Where(vs => vs.id_version == ver_id)
                                               .Select(ss => ss.id_script)
                                               .Contains(s.id)));

        private static readonly Func<DAA, int, IQueryable<db_project>> cGetUserProjects =
            CompiledQuery.Compile((DAA db, int usr_id) =>
                          db.GetTable<db_project>().Where(
                              s => db.GetTable<db_user_project>()
                                       .Where(up => up.id_user == usr_id)
                                       .Select(ss => ss.id_project)
                                       .Contains(s.id)));

        private static readonly Func<DAA, IQueryable<db_project>> cGetActiveProjects =
            CompiledQuery.Compile((DAA db) => db.GetTable<db_project>().Where(p => p.active));

        public static IList<db_script> GetVersionScripts(int ver_id)
        {
            using (var db = new DAA())
            {
                return cGetVersionScripts(db, ver_id).ToList();
            }
        }

        public static IList<db_project> GetUserProjects(int usr_id)
        {
            using (var db = new DAA())
            {
                return cGetUserProjects(db, usr_id).ToList();
            }
        }

        public static IList<db_project> GetActiveProjects()
        {
            using (var db = new DAA())
            {
                return cGetActiveProjects(db).ToList();
            }
        }
    }
}